<?php
/**
 * Short Description  
 *
 * Long Description 
 *
 * @copyright 
 * @version   $Id: System.php 12 2011-04-09 08:58:51Z sandeep.manne@gmail.com $
 */

require_once "Core/System/Factory.php";
require_once "Core/System/Debian.php";

class Core_System
{
	/** @var $_system Core_System_Abstract **/
	private static $_system = "";
	private static $_instance = null;
	
	private function __construct($system)
	{
		self::$_system = Core_System_Factory::getSystem($system);
	}
	
	/**
	 * 
	 * @param string $system
	 * 
	 * @return Core_System
	 */
	public static function getInstance($system = "LINUX")
	{
		//TODO Autodetect system type
		if (ini_get('safe_mode')) {
			throw new Core_System_Exception("php is running in safemode, cannot complete the request");
		} 
		else if (self::$_instance === null) {
			self::$_instance = new self($system);
		}
		
		return self::$_instance;
	}
	
	/**
	 * Get Command Path by calling system
	 * 
	 * @param unknown_type $command
	 */
	public function getCommandPath($command)
	{
		$output = call_user_method("getCommandPath", self::$_system, $command);
		
		return is_string($output[0]) ? $output[0] : new Core_System_Exception("Command '".$command."' not found");
	}
	
	public function installPhpExtension($extension)
	{
		$output = call_user_method("installPhpExtension", self::$_system, $extension);
		
		return (count($output) == 1) ? $output[0] : $output;
	}
	
	public function run($command)
	{
		echo $command . "</br>";
		
		$output = call_user_method("run", self::$_system, $command);
		
		return (count($output) == 1) ? $output[0] : $output; 
	}
	
	public function isCommandExist($command)
	{
		return call_user_method("isCommandExist", self::$_system, $command);
	}
	
	public function checkPhpExtensions($requiredExtensions)
	{
		foreach( $requiredExtensions as $value ) {
            if( !extension_loaded($value) ) {
                throw new Exception("Required PHP extension '{$value}' was not loaded.");
            }
        }
	}
	
	public static function clearCache()
	{
		if ( extension_loaded('apc') ) {
            apc_clear_cache();
        }
	}
}